package com.atguigu.day03.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink06_TransForm_Max_MaxBy {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口获取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.使用flatMap将数据转为JavaBean
        SingleOutputStreamOperator<WaterSensor> flatMap = streamSource.flatMap(new FlatMapFunction<String, WaterSensor>() {
            @Override
            public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                String[] strings = value.split(",");
                out.collect(new WaterSensor(strings[0],Long.parseLong(strings[1]),Integer.parseInt(strings[2])));
            }
        });

        KeyedStream<WaterSensor, Tuple> keyedStream = flatMap.keyBy("id");


        //4.使用Max&MaxBy对比效果
        SingleOutputStreamOperator<WaterSensor> max = keyedStream.max("vc");

        SingleOutputStreamOperator<WaterSensor> maxByWithTrue = keyedStream.maxBy("vc", true);

        SingleOutputStreamOperator<WaterSensor> maxByWithFasle = keyedStream.maxBy("vc", false);

        max.print("max");
        maxByWithTrue.print("maxByWithTrue");
        maxByWithFasle.print("maxByWithFalse");


        env.execute();
    }
}
